package com.example.demoapp.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.GridSpanSizeLookup;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.demoapp.R;
import com.example.demoapp.activity.AudioPlayActivity;
import com.example.demoapp.activity.DocumentsDisplayActivity;
import com.example.demoapp.activity.InformationDisplayActivity;
import com.example.demoapp.activity.VideoDisplayActivity;
import com.example.demoapp.bean.User;
import com.example.demoapp.brvah.adapter.MyBannerAdapter;
import com.example.demoapp.brvah.adapter.ProviderAdapter;
import com.example.demoapp.brvah.bean.MultipleItemBean;
import com.example.demoapp.config.URLs;
import com.example.demoapp.vollley.MySingleton;
import com.google.gson.Gson;
import com.youth.banner.Banner;
import com.youth.banner.config.IndicatorConfig;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.listener.OnPageChangeListener;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ChildFragment extends Fragment {
    private String tabType;

    //recycler_view列表
    private RecyclerView recycler_view;
    //适配器
    ProviderAdapter providerAdapter;
    //数据列表
    List<MultipleItemBean> dataList;

    //Banner
    private Banner banner;
    //banner数据列表
    List<MultipleItemBean> bannerList;
    //MyBannerAdapter
    private MyBannerAdapter myBannerAdapter;
    //mContext
    private Context mContext;
    private List<MultipleItemBean> data;
    //  主界面四选项下标
    private int index;
    private String url;
    private int page;
    private User user;
    private MultipleItemBean oneMultipleItemBean;
    private int mposition;
    private TextView bannertitle;

    private boolean isLiked,isCollected;
    ActivityResultLauncher<Intent> activityLauncher;

    private SharedPreferences preferences;

    private String[] headers;
    public ChildFragment() {
    }

    public ChildFragment(String url, String tabType, int index, int page) {
        this.tabType = tabType;
        this.url = url;
        this.index = index;
        this.page = page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public static ChildFragment newInstance() {
        ChildFragment fragment = new ChildFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityLauncher =registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        // 处理返回的结果
                        isLiked = data.getBooleanExtra("isLike", false);
                        isCollected = data.getBooleanExtra("isCollect", false);
                        if (oneMultipleItemBean.getIsAgree() != (isLiked ? 1 : 0)) {
                            oneMultipleItemBean.setIsAgree(isLiked ? 1 : 0);
                            dataList.set(mposition, oneMultipleItemBean);
                        }
                        if (oneMultipleItemBean.getIsCollect() != (isCollected?1:0)) {
                            oneMultipleItemBean.setIsCollect(isCollected?1:0);
                            dataList.set(mposition, oneMultipleItemBean);
                        }
                    }
                }
        );
        //数据进行返回处理
        mContext = requireContext();
        preferences = mContext.getSharedPreferences("LoginPrefs", Context.MODE_PRIVATE);
        user = new Gson().fromJson(preferences.getString("user",""), User.class);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news_child, container, false);
        //绑定视图
        initView(view);
        //初始化RecycleView
        initRecycleView();
        //初始化Banner
        initBanner();
        //初始化数据
        initListData(false);
        return view;
    }

    //视图绑定
    private void initView(View view) {
        //recycler_view列表
        recycler_view = (RecyclerView) view.findViewById(R.id.recycler_view);
    }
    private void initRecycleView() {
        // 初始化RecyclerView
        recycler_view.setLayoutManager(new GridLayoutManager(mContext, 3));
        //初始化数据
        dataList = new ArrayList<>();
        //初始化适配器
        providerAdapter = new ProviderAdapter(mContext,dataList);
        providerAdapter.setGridSpanSizeLookup(new GridSpanSizeLookup() {
            @Override
            public int getSpanSize(@NonNull GridLayoutManager gridLayoutManager, int viewType, int position) {
                return dataList.get(position).getSpanSize();
            }
        });

        //条目点击事件，查看具体信息
        providerAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                oneMultipleItemBean = dataList.get(position);
                mposition = position;
                changeView(oneMultipleItemBean);
            }
        });
        //设置适配器
        recycler_view.setAdapter(providerAdapter);
    }
    public void initBanner() {
        //初始化Banner视图与控件
        View headView = LayoutInflater.from(mContext).inflate(R.layout.banner_layout, recycler_view, false);
        banner = headView.findViewById(R.id.banner);
        bannertitle = headView.findViewById(R.id.title);

        //添加Banner头部
        providerAdapter.setHeaderView(headView);
        //bannerList初始化
        bannerList = new ArrayList<>();
        //设置BannerAdapter
        myBannerAdapter = new MyBannerAdapter(bannerList);
        //添加生命周期观察者
        banner.addBannerLifecycleObserver(this)
                .setAdapter(myBannerAdapter)
                .setIndicator(new CircleIndicator(mContext))
                .setIndicatorGravity(IndicatorConfig.Direction.RIGHT)
                .setIndicatorSelectedColorRes(R.color.indicator_selected)
                .setIndicatorNormalColorRes(R.color.indicator_normal);
        //指示器改变监听
        banner.addOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                            }

            @Override
            public void onPageSelected(int position) {
                bannertitle.setText(bannerList.get(position).getTitle());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(Object data, int position) {
                oneMultipleItemBean = (MultipleItemBean) data;
                mposition = position;
                changeView(oneMultipleItemBean);
            }
        });
    }

    public void refreshData(List<MultipleItemBean> data, List<MultipleItemBean> bannerData) {
        //Banner数据刷新
        bannerList.clear();
        bannerList.addAll(data);
        myBannerAdapter.notifyDataSetChanged();
        bannertitle.setText(bannerList.get(0).getTitle());
        //recycleView数据刷新
        dataList.clear();
        dataList.addAll(bannerData);
        providerAdapter.notifyDataSetChanged();
    }

    public void refreshData(){
        initListData(false);
    }
    public void loadMoreData(){
        page++;
        initListData(true);
    }

    /**
     * 获取数据
     *
     * @return
     */
    private List<MultipleItemBean> initListData(boolean isLoad) {
        if (!isLoad)data = new ArrayList<>();
        if (!preferences.contains("token")) return data;
        String token = preferences.getString("token","");
        HashMap map = new HashMap();
        map.put("page",String.valueOf(page));
        map.put("pageSize","15");
        map.put("status","1");
        map.put("tabType",this.tabType);
        MySingleton.getInstance(mContext.getApplicationContext()).getRequestQueue().add(new JsonObjectRequest(url, new JSONObject(map),
                new Response.Listener() {
                    @Override
                    public void onResponse(Object response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response.toString());
                            int code = jsonObject.getInt("code");
                            if (code == 200) {
                                JSONObject jdata = jsonObject.getJSONObject("data");
                                int total = jdata.getInt("total");
                                int currentPage = jdata.getInt("currentPage");
                                int currentPageSize = jdata.getInt("currentPageSize");
                                // 从JSONObject中获取"data"字段对应的JSONArray
                                JSONArray dataArray = jdata.getJSONArray("records");
                                // 遍历JSONArray并解析每个对象
                                if (dataArray.length()==0) {
                                    Toast.makeText(mContext, "没有更多数据了", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                for (int i = 0; i < dataArray.length(); i++) {
                                    JSONObject dataObject = dataArray.getJSONObject(i);
                                    MultipleItemBean multipleItemBean = new Gson().fromJson(dataObject.toString(), MultipleItemBean.class);
                                    data.add(multipleItemBean);
                                    Log.d("data", multipleItemBean.toString());
                                }
                                refreshData(data, data);
                            }
                        } catch (Exception e) {
                            Log.i("加载列表错误",e.toString());
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(mContext, "网络出错", Toast.LENGTH_SHORT).show();
            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                headers.put("token", token);
                return headers;
            }
        });
        return data;
    }

    // 视图跳转
    private void changeView(MultipleItemBean oneMultipleItemBean){
        if (oneMultipleItemBean.isSource().equals("1") && oneMultipleItemBean.getLink().startsWith("h")){
            Uri uri = Uri.parse(oneMultipleItemBean.getLink());
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            intent.setData(uri);
            addbrowse(oneMultipleItemBean.getId());
            startActivity(intent);
        } else{
        String html = oneMultipleItemBean.getLink();
        String name = oneMultipleItemBean.getId();
        Intent i = new Intent();
        switch (index){
            case 0:
                i = new Intent(mContext, DocumentsDisplayActivity.class);
                i.putExtra("downloadEnable",oneMultipleItemBean.isDownload());
                html = oneMultipleItemBean.getRichText();
                break;
            case 1:
                i = new Intent(mContext, InformationDisplayActivity.class);
                html = oneMultipleItemBean.getRichText();
                break;
            case 2:
                i = new Intent(mContext, VideoDisplayActivity.class);
                break;
            case 3:
                i = new Intent(mContext, AudioPlayActivity.class);
                break;
        };
        i.putExtra("isLiked", oneMultipleItemBean.getIsAgree());
        i.putExtra("isCollected", oneMultipleItemBean.getIsCollect());
        i.putExtra("LINK", html);
        i.putExtra("NAME", name);
        addbrowse(oneMultipleItemBean.getId());
            activityLauncher.launch(i);
        }

    }


    private void addbrowse(String id){
        HashMap map = new HashMap();
        map.put("targetId",id);
        map.put("targetType",index);
        MySingleton.getInstance(mContext.getApplicationContext()).getRequestQueue().add(new JsonObjectRequest(URLs.add_browse, new JSONObject(map),
                new Response.Listener() {
                    @Override
                    public void onResponse(Object response) {
                        Log.d("BROUSE", "onResponse: 添加记录成功");
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(mContext, "记录历史记录出错", Toast.LENGTH_SHORT).show();
            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                headers.put("token", user.getToken());
                return headers;
            }
        });

    }
}